import React, { Component } from "react";
import { Drawer, Form, Button, Input, Select, Icon, message, Modal, Spin, Switch, Card, Avatar } from "antd";
import { connect } from "dva";
import styles from "./typeNode.less";
import { fetchUserTypeList } from "@/services/hotQuestion";
import SkipModal from "./skipModal";
import { doEditNodeInfo, knowledgeAtlasNodeDetail } from "@/services/knowledgegraph";
import UserSession from "@/UserSession";

const { Option } = Select;

class SkipNode extends Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			loading: false,
			nodeInfo: null,
			userTypeList: [],
			nodeDetail: null,
			skipObj: null,
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}

	getUserTypeList = async () => {
		const res = await fetchUserTypeList({ current: 1, size: 999999 });
		this.setState({
			userTypeList: res && res.records ? res.records : [],
		});
	};

	onClose = () => {
		this.setState({
			visible: false,
		});
	};

	openDrawer = (node) => {
		const nodeInfo = node._cfg.model;
		this.setState(
			{
				visible: true,
				nodeInfo,
			},
			() => {
				this.getUserTypeList();
				this.getNodeDetail(nodeInfo);
			}
		);
	};

	/**
	 * 获取节点编辑详情
	 */
	getNodeDetail = async (nodeInfo) => {
		const { dispatch, form } = this.props;
		if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeAtlasNodeDetail({ nodeId: nodeInfo.id });
			console.log(res);
			let skipObj = null;
			if (res.jumpQaType) {
				skipObj = {
					basicQuestion: res.jumpQaName,
					id: res.jumpQaId,
					qaType: res.jumpQaType,
					localType: res.jumpQaLocalType,
				};
			}
			this.setState(
				{
					nodeDetail: {
						...res,
						disabled: !res.disabled,
					},
					skipObj,
				},
				() => {
					form.setFieldsValue({
						title: res.title,
						disabled: !res.disabled,
						userTypeIdList: res.userTagIdList && res.userTagIdList.length
							? res.userTagIdList.map((item) => {
								return item.id;
							})
							: [],
					});
				}
			);
		} else {
			dispatch({
				type: "nodeEdit/getNodeDetailByNodeId",
				payload: { id: nodeInfo.id },
				callback: (res) => {
					let skipObj = null;
					if (res.jumpQaType) {
						skipObj = {
							basicQuestion: res.jumpQaName,
							id: res.jumpQaId,
							qaType: res.jumpQaType,
							localType: res.jumpQaLocalType,
						};
					}
					this.setState(
						{
							nodeDetail: {
								...res,
								disabled: !res.disabled,
							},
							skipObj,
						},
						() => {
							form.setFieldsValue({
								title: res.title,
								disabled: !res.disabled,
								userTypeIdList: res.userTagIdList && res.userTagIdList.length
									? res.userTagIdList.map((item) => {
										return item.id;
									})
									: [],
							});
						}
					);
				},
			});
		}
	};

	saveNode = () => {
		const { form } = this.props;
		const { skipObj, nodeDetail, userTypeList } = this.state;
		form.validateFields(async (err, values) => {
			if (err) {
				return false;
			}

			if (skipObj) {
				values.jumpQaId = skipObj.id;
				values.jumpQaType = skipObj.qaType;
				values.jumpQaLocalType = skipObj.localType;
			} else {
				values.jumpQaId = null;
				values.jumpQaType = null;
				values.jumpQaLocalType = false;
			}

			let disabled = false;
			if (values.disabled == undefined) {
				disabled = false;
			} else {
				disabled = !values.disabled;
			}
			let userTagIdList = [];
			if (values.userTypeIdList && values.userTypeIdList.length > 0) {
				userTypeList.forEach(item => {
					if (values.userTypeIdList.indexOf(item.id) > -1) {
						userTagIdList.push({ id: item.id, tagName: item.tagName });
					}
				})
			};
			delete values.userTypeIdList;
			const res = await doEditNodeInfo({
				...values,
				disabled,
				userTagIdList,
				atlasId: nodeDetail.atlasId,
				id: nodeDetail.id,
				basicQuestion: "",
				sensitive: nodeDetail.sensitive,
			});
			console.log(res);
			if (res.code === 0) {
				message.success("保存成功");
				this.setState({ visible: false, }, () => {
					this.props.resetNodeTitle(values.title, disabled);
				});
			}
		});
	};

	showSkipModal = () => {
		this.SkipModalRef.showModal(this.state.skipObj);
	};

	addSkip = (record, type) => {
		this.setState({
			skipObj: record || null,
		});
	};

	render() {
		const { visible, loading, nodeInfo, userTypeList, skipObj } = this.state;
		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
			labelCol: {
				xs: { span: 26 },
				sm: { span: 4 },
			},
			wrapperCol: {
				xs: { span: 22 },
				sm: { span: 20 },
			},
		};
		const formItemLayoutWithOutLabel = {
			wrapperCol: {
				xs: { span: 22, offset: 4 },
				sm: { span: 20, offset: 4 },
			},
		};
		return (
			<Drawer
				title='编辑跳转节点'
				width={680}
				onClose={() => this.onClose()}
				visible={visible}
				bodyStyle={{ paddingBottom: 80 }}
			>
				<div className={styles.label}>基础设置</div>
				<Form>
					<Form.Item label='标题' {...formItemLayout}>
						{getFieldDecorator("title", {
							rules: [{ required: true, message: "标题不能为空" }],
						})(
							<Input
								disabled={UserSession.isSystemKnowledge()}
								style={{ width: "88%" }}
								placeholder='标题'
							/>
						)}
					</Form.Item>

					{UserSession.isSystemDataKnowledge() ? null : (
						<Form.Item label='是否启用' {...formItemLayout}>
							{getFieldDecorator("disabled", {
								valuePropName: "checked",
							})(<Switch checkedChildren='启用' unCheckedChildren='禁用' />)}
						</Form.Item>
					)}
					{UserSession.isSystemDataKnowledge() ? null : (
						<Form.Item label='适用标签' {...formItemLayout}>
							{getFieldDecorator("userTypeIdList")(
								<Select mode='multiple' style={{ width: "88%" }} placeholder='适用标签'>
									{userTypeList.map((item) => (
										<Option value={item.id} key={item.id}>{item.tagName}</Option>
									))}
								</Select>
							)}
						</Form.Item>
					)}
				</Form>
				<div className={styles.label}>跳转到</div>
				<div style={{ padding: 20 }}>
					{skipObj ? (
						<div>
							{skipObj.qaType == 3 ? (
								<>
									{/* <Card className={styles.card}>
										<Card.Meta
											avatar={
												<Avatar className={styles.cardAvatar}>
													{skipObj.basicQuestion.substr(0, 1)}{" "}
												</Avatar>
											}
											title={
												<a
													title={skipObj.basicQuestion}
													style={{
														width: "100%",
														display: "block",
														overflow: "hidden",
														whiteSpace: "nowrap",
														textOverflow: "ellipsis",
													}}>
													{skipObj.basicQuestion}
												</a>
											}
										/>
									</Card> */}
									<div style={{ display: 'flex', alignItems: 'center' }}>
										<span style={{ background: '#e7e7e7', padding: '0 5px', borderRadius: '5px' }}>多轮</span>
										<div
											style={{
												padding: 10,
												backgroundColor: "rgba(85, 85, 85, 1)",
												borderRadius: 50,
												color: "white",
												position: 'relative',
												width: 'calc(100% - 52px)',
												marginLeft: '12px',
											}}
										>
											{skipObj.basicQuestion}
										</div>
									</div>
								</>
							) : (
								<div style={{ display: 'flex', alignItems: 'center' }}>
									<span style={{ background: '#e7e7e7', padding: '0 5px', borderRadius: '5px' }}>问答</span>
									<div
										style={{
											padding: 10,
											backgroundColor: "rgba(85, 85, 85, 1)",
											borderRadius: 50,
											color: "white",
											position: 'relative',
											width: 'calc(100% - 52px)',
											marginLeft: '12px',
										}}
									>
										{skipObj.basicQuestion}
									</div>
								</div>
							)}
							{!UserSession.isSystemKnowledge() && (
								<span
									onClick={this.showSkipModal}
									style={{
										cursor: "pointer",
										padding: 10,
										marginTop: 10,
										display: "block",
										color: "#3e5bff",
									}}
								>
									重新选择
								</span>
							)}
						</div>
					) : (
						<Button onClick={this.showSkipModal} disabled={UserSession.isSystemKnowledge()}>选择跳转对象</Button>
					)}
				</div>
				<div
					style={{
						position: "absolute",
						right: 0,
						bottom: 0,
						width: "100%",
						borderTop: "1px solid #e9e9e9",
						padding: "10px 16px",
						background: "#fff",
						textAlign: "right",
					}}>
					<Button onClick={this.onClose} style={{ marginRight: 8 }}>
						取消
					</Button>
					<Button onClick={this.saveNode} type='primary'>
						保存
					</Button>
				</div>
				<SkipModal
					onRef={(ref) => (this.SkipModalRef = ref)}
					add={this.addSkip}
					rootCategoryId={this.props.rootCategoryId}
				/>
			</Drawer>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(SkipNode));
